package org.xurui.bsj.protocol.command.impl;

import lombok.extern.slf4j.Slf4j;
import org.hswebframework.web.bean.FastBeanCopier;
import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.core.message.function.FunctionInvokeMessageReply;
import org.jetlinks.core.message.function.FunctionParameter;
import org.xurui.bsj.protocol.cache.ConcurrentMapCache;
import org.xurui.bsj.protocol.command.CmdCodec;
import org.xurui.bsj.protocol.enums.CommandEnum;
import org.xurui.bsj.protocol.msg.BsjMessage;
import org.xurui.bsj.protocol.msg.BsjMessageBuilder;
import org.xurui.bsj.protocol.utils.ArrayUtils;
import org.xurui.bsj.protocol.utils.BinaryUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 4.2.9.设置情景模式
 */
@Slf4j
public class CmdCodec_SET_MODEL implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.SET_MODEL.name().equals(cmd);
    }

    @Override
    public List<DeviceMessage> parsePayload(BsjMessage payload, FromDeviceMessageContext context) {
        //例子：[35380100360174,898600MFSSYYGXXXXXXP,201805082000001000,SET_MODEL, 2,20180528111820,1,0]
        FunctionInvokeMessageReply report = FunctionInvokeMessageReply.create();
        report.setDeviceId(payload.getHeader().getDeviceNo());
        report.setFunctionId(payload.getHeader().getCmd());
        Object messageIdObj = ConcurrentMapCache.getInstance().getAndRemove(payload.getHeader().getOrderNo());
        String messageId = messageIdObj==null?null:messageIdObj.toString();
        if(messageId==null){
            messageId = payload.getHeader().getOrderNo();
        }
        report.setMessageId(messageId);
        report.setTimestamp(System.currentTimeMillis());
        Map<String, Object> properties = new HashMap<>();
        String tempBody = payload.getTempBody();
        String[] tempBodyArr = tempBody.split("@");
        //properties.put("header", FastBeanCopier.copy(payload.getHeader(), HashMap::new));
        properties.put("header", payload.getHeader().toMap());
        //应答状态(0=设置成功;1=设置异常;)
        properties.put("responseStatus", ArrayUtils.getStrByIndex(tempBodyArr,0));
        report.setOutput(properties);
        return genDeviceMessage(report);
    }

    @Override
    public EncodedMessage encodeMessage(CommonDeviceMessage message,String zzs) {
        //平台下发消息
        //例子：[35380100360174,898600MFSSYYGXXXXXXP,201805082000001000,SET_MODEL, 1,20180528111820,7,1@0@0@0]
        /**
         * 报文体格式： 静音
         *            @响玲
         *            @限制呼入
         *            @限制呼出
         * 字段说明:   1.静音：0不静音1静音
         *            2.响玲：0不响铃1响玲
         *            3.限制呼入: 0=不限制呼入，1=限制呼入
         *            4.限制呼出: 0=不限制呼出，1=限制呼出 注意：静音和响玲不能同时生效
         */
        if(message instanceof FunctionInvokeMessage) {
            FunctionInvokeMessage m = (FunctionInvokeMessage) message;
            List<FunctionParameter> params = m.getInputs();
            Map<String, Object> paramsMap = params.stream()
                .collect(Collectors.toMap(FunctionParameter::getName, FunctionParameter::getValue));
            String  mute="";
            if(paramsMap.get("mute")!=null && !paramsMap.get("mute").equals("")) {
                mute=paramsMap.get("mute").toString();
            }

            String  ring="";
            if(paramsMap.get("ring")!=null && !paramsMap.get("ring").equals("")) {
                ring=paramsMap.get("ring").toString();
            }

            String  incomCall="";
            if(paramsMap.get("incomCall")!=null && !paramsMap.get("incomCall").equals("")) {
                incomCall=paramsMap.get("incomCall").toString();
            }

            String  outcomCall="";
            if(paramsMap.get("outcomCall")!=null && !paramsMap.get("outcomCall").equals("")) {
                outcomCall=paramsMap.get("outcomCall").toString();
            }

            StringBuffer sb = new StringBuffer();
            sb.append(mute);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(ring);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(incomCall);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(outcomCall);

            return BsjMessageBuilder.create().buildBsjFunctionInvoickMessage(m,sb.toString());
        }else{
            if (log.isDebugEnabled()) {
                log.debug("非FunctionInvokeMessage指令{}消息{}",CommandEnum.SET_MODEL.name(),message);
            }
            return null;
        }

    }
}
